package com.jlin.covertcode;

import java.io.UnsupportedEncodingException;

/**
 * @description: 
 * @SEE http://en.wikipedia.org/wiki/GBK
 * @see GBK编码表 http://wenku.baidu.com/view/541aec26aaea998fcc220ecf?from_page=view&from_mod=download 
 * @author:lijilin@hitao.com on 2014-1-14 下午5:22:20
 *
 */

public class GBKDecode {
	
	private static int single = 0x7f; 
	private static int HIGH_START = 0x81;
	private static int HIGH_END = 0xFE;
	private static int LOW_START = 0x40;
	private static int LOW_END = 0xFE;
	private static int LOW_EXCEPT = 0x7F;
	
	public static void main(String[] args) throws Exception {
		
		byte[] bytes = new String("傽a春a来江水绿如蓝").getBytes("GBK");
		byte[] byteSplit = new byte[7];
		System.arraycopy(bytes, 0, byteSplit, 0, byteSplit.length);
		
		isChinese(byteSplit);
	}
	
	public static void isChinese(byte[] bytes) {
		int position = -1;
		for (int i=0; i< bytes.length;) {
			//为什么要&0xff http://franksinger.iteye.com/blog/614540
			if((bytes[i]&0xff) >= HIGH_START && (bytes[i]&0xff) <= HIGH_END){
				if(i == bytes.length-1) {
					position = bytes.length-1;
					break;
				} else if(i == bytes.length -2){
					position = bytes.length;
					break;
				} else {
					i += 2;
				}
			} else {
				if(i == bytes.length-1){
					position = i;
					break;
				}
				i ++;
			}
		}

		try {
			System.out.println(new String(bytes, 0, position, "GBK"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	//三种方法
	//1.区位码大于0xff 字节转16进制然后减去0xA0 ，这个说不通，
	//2.转为int后为负数，不行， 傽这个字的第二个字节就不为负数，但是首字节都是负数，因为区间为0x81(10000001) - 0xFE(11111110)，第八位为1，那就是符号位
	//3.高位码大于0x81 小于 0xfe，觉得第三种方式最合理
	
	public static void encode() { 
        String name = "春来江水绿如蓝"; 
        try { 
            byte[] iso8859 = name.getBytes("ISO-8859-1"); 
            bytesToHexString(iso8859); 
            byte[] gb2312 = name.getBytes("GB2312"); 
            bytesToHexString(gb2312); 
            byte[] gbk = name.getBytes("GBK"); 
            bytesToHexString(gbk); 
            byte[] utf16 = name.getBytes("UTF-16"); 
            bytesToHexString(utf16); 
            byte[] utf8 = name.getBytes("UTF-8"); 
            bytesToHexString(utf8); 
        } catch (UnsupportedEncodingException e) { 
            e.printStackTrace(); 
        } 
 }
	
	public static String bytesToHexString(byte[] src){  
	    StringBuilder stringBuilder = new StringBuilder("");  
	    if (src == null || src.length <= 0) {  
	        return null;  
	    }  
	    for (int i = 0; i < src.length; i++) {  
	        int v = src[i] & 0xFF;  
	        
	        String hv = Integer.toHexString(v); 
	        
	        if (hv.length() < 2) {  
	            stringBuilder.append(0);  
	        }  
	        stringBuilder.append(hv);  
	    }  
	    System.out.println(src.length+","+stringBuilder.toString());
	    return stringBuilder.toString();  
	}
	

}
